package leetcode.weekly.week325;

//Solution2Test
public class Solution2 {
	public int takeCharacters(String s, int k) {
		// aabaaaacaabc 2
		char[] cs = s.toCharArray();
		int[] h = new int[3];
		for (char c : cs) {
			h[c - 'a']++;
		}
		for (int i = 0; i < 3; i++) {
			int num = h[i];
			if (num < k) {
				return -1;
			}
			h[i] -= k;
		}
		int t = cs.length;
		int l = 0, r = 0;
		int[] cnt = new int[3];
		int ans = Integer.MAX_VALUE;
		while (r < t) {
			int num = cs[r] - 'a';
			cnt[num]++;
			while (cnt[num] > h[num] && l <= r) {
				cnt[cs[l] - 'a']--;
				l++;
			}
			ans = Math.min(ans, t - (r - l + 1));
			r++;
		}
		return ans;
	}

}
